<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>地址选择器</title>
    <link rel="stylesheet" href="__CDN__/assets/css/frontend.min.css"/>
    <link rel="stylesheet" href="__CDN__/assets/libs/font-awesome/css/font-awesome.min.css"/>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        #container {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
        }

        .confirm {
            position: absolute;
            bottom: 30px;
            right: 4%;
            z-index: 99;
            height: 50px;
            width: 50px;
            line-height: 50px;
            font-size: 15px;
            text-align: center;
            background-color: white;
            background: #1ABC9C;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 50%;
        }

        .search {
            position: absolute;
            width: 400px;
            top: 0;
            left: 50%;
            padding: 5px;
            margin-left: -200px;
        }
    </style>
</head>
<body>
<div class="search">
    <div class="input-group">
        <input type="text" id="place" name="q" class="form-control" placeholder="输入地点"/>
        <span class="input-group-btn">
            <button type="button" name="search" id="search-btn" class="btn btn-success">
                <i class="fa fa-search"></i>
            </button>
        </span>
    </div>
</div>
<div class="confirm">确定</div>
<div id="container"></div>

<script charset="utf-8" src="//map.qq.com/api/js?v=2.exp&libraries=place&key={$config.tencentkey|default=''}"></script>
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>

<script type="text/javascript">
    $(function () {
        var map, marker, geocoder, infoWin, searchService, keyword, address;
        address = "{$address}";
        var init = function () {
            var center = new qq.maps.LatLng({$lat}, {$lng});
            map = new qq.maps.Map(document.getElementById('container'), {
                center: center,
                zoom: parseInt("{$config.zoom}")
            });

            //实例化信息窗口
            infoWin = new qq.maps.InfoWindow({
                map: map
            });

            //地址解析
            geocoder = new qq.maps.Geocoder({
                complete: function (result) {
                    var addressInfo = result.detail.addressComponents;
                    var address = addressInfo.province + addressInfo.city + addressInfo.district;
                    if (addressInfo.streetNumber == '') {
                        address += addressInfo.street;
                    } else {
                        address += addressInfo.streetNumber;
                    }
                    showMarker(result.detail.location, address);
                    showInfoWin(result.detail.location, address);
                }
            });

            //查询poi类信息
            searchService = new qq.maps.SearchService({
                complete: function (results) {
                    if (results.type === "CITY_LIST") {
                        searchService.setLocation(results.detail.cities[0].cityName);
                        searchService.search(keyword);
                        return;
                    }
                    if (typeof results.detail.pois === 'undefined') {
                        alert("未搜索到相关信息");
                        return;
                    }
                    var latlngBounds = new qq.maps.LatLngBounds();
                    var pois = results.detail.pois;
                    for (var i = 0; i < pois.length; i++) {
                        var poi = pois[i];
                        if (poi.type != 0) {
                            geocoder.getAddress(poi.latLng);
                        } else {
                            showMarker(poi.latLng, poi.address);
                            showInfoWin(poi.latLng, poi.address);
                        }
                        latlngBounds.extend(poi.latLng);
                        //只显示第一个
                        break;
                    }
                    map.fitBounds(latlngBounds);
                }
            });


            //初始化marker
            showMarker(center);
            if (address) {
                showInfoWin(center, address);
            } else {
                geocoder.getAddress(center);
            }

            //实例化自动完成
            var ap = new qq.maps.place.Autocomplete(document.getElementById('place'));

            //添加监听事件
            qq.maps.event.addListener(ap, "confirm", function (res) {
                keyword = res.value;
                searchService.search((this.place ? this.place.address : "") + keyword);
            });

            //地图点击
            qq.maps.event.addListener(
                map,
                'click',
                function (event) {
                    try {
                        var latLng = event.latLng,
                            lat = latLng.getLat().toFixed(5),
                            lng = latLng.getLng().toFixed(5);
                        var location = new qq.maps.LatLng(lat, lng);
                        //调用获取位置方法
                        geocoder.getAddress(location);
                        infoWin.setPosition(location);
                        marker.setPosition(location);
                    } catch (e) {
                        console.log(e);
                    }
                }
            );
        };

        //显示info窗口
        var showInfoWin = function (position, title) {
            infoWin.open();
            infoWin.setContent(title);
            infoWin.setPosition(position);
        };

        //实例化marker和监听拖拽结束事件
        var showMarker = function (latLng, title) {
            marker && marker.setMap(null);
            marker = new qq.maps.Marker({
                map: map,
                position: latLng,
                draggable: true,
                title: title || '拖动图标选择位置'
            });

            //监听拖拽结束
            qq.maps.event.addListener(marker, 'dragend', function (event) {
                var latLng = event.latLng,
                    lat = latLng.getLat().toFixed(5),
                    lng = latLng.getLng().toFixed(5);
                var location = new qq.maps.LatLng(lat, lng);
                //调用获取位置方法
                geocoder.getAddress(location);
            });
        };

        var close = function (data) {
            var index = parent.Layer.getFrameIndex(window.name);
            var callback = parent.$("#layui-layer" + index).data("callback");
            //再执行关闭
            parent.Layer.close(index);
            //再调用回传函数
            if (typeof callback === 'function') {
                callback.call(undefined, data);
            }
        };

        //点击确定后执行回调赋值
        $(document).on('click', '.confirm', function () {
            var zoom = map.getZoom();
            var data = {lat: infoWin.position.lat.toFixed(5), lng: infoWin.position.lng.toFixed(5), zoom: zoom, address: infoWin.content};
            close(data);
        });

        //点击搜索按钮
        $(document).on('click', '#search-btn', function () {
            if ($("#place").val() == '')
                return;
            searchService.search($("#place").val());
        });

        init();
    });
</script>
</body>
</html>
